import axios from "axios";
import cookin from "js-cookie";
import qs from "qs";
import router from "@/router";
import NProgress from "nprogress";
// import { ElMessage } from "element-plus";
import store from "@/store";

let baseURL = "";

let host = "http://192.168.1.188:8080";

if (process.env.NODE_ENV === "development") {
  baseURL = "http://192.168.1.188:8080/m.api";
} else {
  baseURL = "http://192.168.1.188:8080/m.api";
}
const instance = axios.create({
  baseURL,
  host,
});
// console.log(store);
//请求和响应拦截可以根据实际项目需求进行编写
instance.interceptors.request.use(
  (config) => {
    // 请求发起前拦截
    //设置全局请求头
    NProgress.start();
    config.headers["AdminToken"] = cookin.get("token");
    // console.log("请求拦截", config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
const ruquestype = ["_mt=edit", "_mt=create","_mt=delete"]
instance.interceptors.response.use(async function (response) {
  // 响应拦截（请求返回后拦截）
  let { data } = response;
  let { errno, errmsg } = data;
  let path = router.currentRoute.value.fullPath;
  if (10006 === errno) { //令牌过期处理
    //获取接口数据类型
    
    const configdata = response.config.data;
    var index = -1;
    for (let i = 0; configdata && i < ruquestype.length; i++) {
      const element = ruquestype[i];
      // console.log(element);
      index = configdata.indexOf(element);
      console.log(index);
      if (index > -1) { //找到之后退出循环
        break;
      }
    }
    if (-1 === index) { //需要重新获取令牌
      router.replace({ path: "/login", query: { back: path } });
      return;
    } else { //需要无痛刷新令牌
      const { username, password } = store.state.addusermodules.cunc;
      // console.log(username,password);
      //重新获取令牌
      let logindata = { _gp:"admin", _mt:"login", username,password}; //获取账号密码
      const { errno, errmsg, data } = await post(logindata); //需要同步调取
      if (200 == errno) {
        cookin.set("token",data);
      } else {
        router.replace({ path: "/login", query: { back: path } }); //登录后需要跳回地址
        return 
      }
      //重新发送上次请求
      return  instance.request(response.config)
    }
  }
  NProgress.done();
  return data;
  },
  function (error) {
    NProgress.done();
    console.log(error);
    return Promise.reject(error);
  }
);
//get方法
function get(params) {
  return instance.get("", { params });
}
//post方法
function post(err, params) {
  // console.log(err);
  return instance.post("", qs.stringify(err), { params });
}
function upload(url, data) {
  return instance.post(url, data);
}
export default {
  get,
  post,
  host,
  upload,
};
